﻿using System;
using System.Management.Automation.Provider;

namespace PSPROOFUtils
{
    /// <summary>
    /// Write data sets to the dataset.
    /// </summary>
    class DSContentWriter : IContentWriter
    {
        /// <summary>
        /// The dataset we are writing to.
        /// </summary>
        private ProofDataSetItem _ds;

        public DSContentWriter(ProofDataSetItem ds, bool verify)
        {
            // TODO: Complete member initialization
            this._ds = ds;
            this._verify = verify;
        }

        /// <summary>
        /// Update the server when we have closed this I/O operation.
        /// </summary>
        public void Close()
        {
            _ds.UpdateServer(_verify);
        }

        /// <summary>
        /// There are only certian seek operations we allow.
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="origin"></param>
        public void Seek(long offset, System.IO.SeekOrigin origin)
        {
            if (offset != 0)
                throw new ArgumentException(string.Format("Unable to seek to the middle of dataset '{0}' - only the start or end!", _ds.Name));

            //
            // Nothing to do if we are moving 0 from where we are now!
            //

            if (origin == System.IO.SeekOrigin.Current)
                return;

            //
            // If we want to go back to the start that is like resetting all the files up there.
            //

            if (origin == System.IO.SeekOrigin.Begin)
                _ds.ClearAllFiles();
        }

        /// <summary>
        /// The objects are coming in that we want to write into this. Hopefully someone will understand them! :-)
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public System.Collections.IList Write(System.Collections.IList content)
        {
            foreach (var item in content)
            {
                _ds.AddItem(item);
            }

            return content;
        }

        /// <summary>
        /// Nothing to do when we clean up here!
        /// </summary>
        public void Dispose()
        {
        }


        /// <summary>
        /// True if we should run the "verify" when we do the update.
        /// </summary>
        public bool _verify { get; set; }
    }
}
